<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>数组取真与数组分块</title>
</head>
<body>
  <!-- 
    1. compact(): 返回数组中所有真值元素组成的新数组
    2. chunk(size): 将数组拆分成多个 size 长度的区块，每个区块组成小数组,整体组成一个二维数组
   -->
  <script>
    /* 1. compact() : 利用filter()实现 */
    Array.prototype.compact = function () {
      return this.filter(item => item)
    }
    

    /* 2. chunk(size) : 利用slice()实现 */
    Array.prototype.chunk = function (size) {
      if (this.length===0) {
        return []
      }
      size = size || 1

      var resultLength = Math.ceil(this.length / size)
      var resultArr = new Array(resultLength)
      var resultIndex = 0
      var index = 0
      while (resultIndex < resultLength) {
        resultArr[resultIndex++] = this.slice(index, index += size)
      }
      return resultArr
    }
  </script>

  <script>
    console.log([0, 1, false, true, '', 'abc'].compact()) // [1, true, 'abc']
    console.log([1, 2, 3, 4, 5, 6, 7].chunk(3)) // [[1,2,3], [4,5,6],[7]]
    console.log([1, 2, 3, 4, 5, 6, 7].chunk())// [[1],[2],[3],[4],[5],[6],[7]]
    console.log([1, 2, 3, 4, 5, 6, 7].chunk(8))// [[1, 2, 3, 4, 5, 6, 7]]
  </script>
</body>
</html>